//Usage: ./cropImage "input_image" "output_image"

//NEED TO SET ROI crop coords in line 44 in cvRect() ...
//output_image = crop(input_image, cvRect(x_origin, y_origin, x_width, y_width));

#include "cropImage.h"

IplImage* input_image;
IplImage* output_image;
IplImage* src;
int i;
char* outputImageFileName;

IplImage* crop(IplImage* src, CvRect roi)
{
	output_image = cvCreateImage(cvSize(roi.width,roi.height), src->depth, src->nChannels);
	
	cvSetImageROI(src, roi);
	
	cvCopy(src, output_image);
	cvResetImageROI(src);
	
	return output_image;
}

int main(int argc, char *argv[])
{
	printf("\nCommand-line arguments entered: \n");
	printf("-------------------------------\n");
	printf(" argc = %d \n", argc);
	printf("*argv = %s \n", *argv);
	int options;

	for (options = 1; options < argc; ++options)
	{
	    printf(" argv[%d] = %s \n\n", options, argv[options]);
	}

	for (i = 1; i < argc; ++i)
	{
		input_image = cvLoadImage(argv[i], CV_LOAD_IMAGE_UNCHANGED);
		outputImageFileName = argv[++i];
	}
	output_image = crop(input_image, cvRect(150, 150, 175, 175));	
	cvSaveImage(outputImageFileName, output_image, 0);    	

	printf("input_image = %s\n", argv[i]); 
	printf("input_image Width = %d\n", input_image->width);
	printf("input_image Height = %d\n", input_image->height);
	printf("input_image nChannels = %d\n", input_image->nChannels);   
	printf("input_image Depth = %d\n", input_image->depth); 		 

	printf("output_image = %s\n", argv[i]); 
	printf("output_image Width = %d\n", output_image->width);
	printf("output_image Height = %d\n", output_image->height);
	printf("output_image nChannels = %d\n", output_image->nChannels);   
	printf("output_image Depth = %d\n", output_image->depth); 		 

	cvNamedWindow("input_image",1); // create a new window with autosize
	cvShowImage("input_image", input_image); //& display the image
	cvWaitKey(0); //wait for (space) key to close the window			

	cvNamedWindow("output_image",1); // create a new window with autosize
	cvShowImage("output_image", output_image); //& display the image
	cvWaitKey(0); //wait for (space) key to close the window			

	return 0;
}



// ///////////////////////////////////////////////////////

/*
From:
http://mehrez.kristou.org/opencv-image-cropping/
downloaded on 2011-05-07

//Here is a useful function to crop an image or to get the region of interest (ROI).

IplImage* crop( IplImage* src,  CvRect roi){
  // Must have dimensions of output image
  IplImage* cropped = cvCreatImage( cvSize(roi.width,roi.height), src->depth, src->nChannels )

  // Say what the source region is
  cvSetImageROI( src, roi );

  // Do the copy
  cvCopy( src, cropped );
  cvResetImageROI( src );

  return cropped;
}

usage will be like this:

IplImage* cropped = crop(source, cvRect( 0,0, 1280,500 ));Be careful not to give a cvRect bigger then source image. It will crash your program with an awful error message.
*/
